package com.zxl.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class FlexPaperUtil {
	private static final String javacommand = "java -jar";
	private static final String SPACE = " ";
	private static final String jodname = "jodconverter-cli-2.2.2.jar";
	
	private static String pdf2swfpath = "D:\\Program Files (x86)\\SWFTools\\";
	private static String pdf2swfname = "pdf2swf.exe";
	private static Runtime runtime = Runtime.getRuntime();
	
	private static FlexPaperUtil instance;
	
	
	public static FlexPaperUtil getInstance(){
		if(null == instance){
			synchronized (FlexPaperUtil.class) {
				instance = new FlexPaperUtil();
			}
		}
		return instance;
	}

	public void docToSwf(String docPath, String outPath) throws Exception {
		String pdfPath = outPath.substring(0, outPath.length()-3) + "pdf";
		
		int n = docPath.lastIndexOf(".");
		String ext = docPath.substring(n+1);
		
		if(ext.equals("pdf")){
			pdfPath = docPath;
		}else{
			docToPdf(docPath, pdfPath);
		}
		pdfToSwf(pdfPath, outPath);
	}
	
	public void docToPdf(String docPath, String outPath) throws Exception {
		String libpath = this.getClass().getResource("/").getPath();
		libpath = libpath.substring(1, libpath.length() - "classes/".length()) + "lib/";
		String command = javacommand + SPACE + libpath + jodname + SPACE + docPath + SPACE + outPath;
		System.out.println("docToPdf:" + command);
		Process process = runtime.exec(command);
		process.waitFor();
		process.destroy();
		File outFile = new File(outPath);
		if(outFile.exists()){
//			log.info("docToPdf success.........");
		}else{
//			log.info("docToPdf error.........");
		}
	}
	
	public int pdfToSwf(String docPath, String outPath) throws Exception {
		String command = pdf2swfpath + pdf2swfname + SPACE + docPath + SPACE + outPath;
		System.out.println("pdfToSwf:" + command);
		Process process = runtime.exec(command);
		
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while (bufferedReader.readLine() != null);
          
        try {
        	process.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File outFile = new File(outPath);
		if(outFile.exists()){
//			log.info("pdfToSwf success.........");
		}else{
//			log.info("pdfToSwf error.........");
		}
        return process.exitValue();
	}

	public static void main(String[] args) throws Exception {
		FlexPaperUtil.getInstance();
		FlexPaperUtil fpu = new FlexPaperUtil();
		fpu.docToSwf("C:\\Users\\Lenovo\\Desktop\\test.docx", "C:\\Users\\Lenovo\\Desktop\\test.swf");
	}

}
